const path = require("path");
const TerserPlguin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  mode: "production",
  entry: "./src/main.js",
  devtool: false,
  output: {
    filename: "js/[name]_[chunkhash:5].js",
    path: path.resolve(__dirname, "./dist"),
    clean: true,
  },
  target: "web",
  resolve: {
    extensions: [".js", ".json", ".jsx", ".vue", ".ts"],
  },
  devServer: {
    static: ["public", "common"],
    open: true,
    host: "0.0.0.0",
    port: 3000,
    liveReload: false,
    compress: true,
    historyApiFallback: true,
  },
  optimization: {
    chunkIds: "deterministic",
    splitChunks: {
      chunks: "all",
    },
    minimize: true, // 告之webpack 使用terser
    minimizer: [
      // js 压缩配置
      new TerserPlguin({
        extractComments: true, // 是否提取注释
        parallel: true, // 使用多进程并发提高构建
        terserOptions: {
          compress: {
            // 设置压缩相关配置
            arguments: true,
            unsafe: false,
          },
          mangle: true, // 是否丑化
          // toplevel: false, // 顶层变量是否转换
          keep_fnames: true, // 是否保留函数名称
        },
      }),
      new CssMinimizerWebpackPlugin({
        parallel: true,
      }),
    ],
  },
  module: {
    rules: [
      {
        test: /\.m?jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new TerserPlguin(),
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name]_[hash:6].css",
      chunkFilename: "css/[name]_[hash:6].css",
    }),
  ],
};
